package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.LoginDto;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    private HttpServletRequest request;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @Autowired
    private UserService userService;
    //发送短信验证码
    @PostMapping("/sendMsg")
    public R sendMsg(@RequestBody LoginDto loginDto){

        //Random random = new Random();
        //int code = random.nextInt(900000)+100000;

        String code = ValidateCodeUtils.generateValidateCode4String(6);

        //SendSms.sendMsg(loginDto.getPhone(),code+"");

        System.out.println("验证码:"+code);
        redisTemplate.opsForValue().set(loginDto.getPhone(),code);
//        HttpSession session = request.getSession();
//        session.setAttribute(loginDto.getPhone(),code);

        return R.success("短信发送成功");
    }
    //验证码登录
    @PostMapping("/login")
    public R login(@RequestBody LoginDto loginDto){
        //1). 获取前端传递的手机号和验证码
        if (loginDto == null){
            return R.error("参数错误");
        }
        //2). 从Session中获取到手机号对应的正确的验证码
        HttpSession session = request.getSession();
       // String code = (String) session.getAttribute(loginDto.getPhone());
        String code = redisTemplate.opsForValue().get(loginDto.getPhone());
        redisTemplate.expire(loginDto.getPhone(),60, TimeUnit.SECONDS);
        //3). 进行验证码的比对 , 如果比对失败, 直接返回错误信息
        if (code == null){
            return R.error("请先获得验证码");
        }
        if (!code.equals(loginDto.getCode())){
            return R.error("验证码错误");
        }
        //4). 如果比对成功, 需要根据手机号查询当前用户
        User user = userService.findByPhone(loginDto.getPhone());
        if (user == null){
            //如果用户不存在, 则自动注册一个新用户
            User userNew = userService.add(loginDto.getPhone());
            session.setAttribute("userId",userNew.getId());
            return R.success("注册成功");
        }
        //5). 将登录用户的ID存储Session中
        session.setAttribute("userId",user.getId());
        return R.success("登录成功");
    }
    //todo 退出登录
    @PostMapping("loginout")
    public R loginout(){
        HttpSession session = request.getSession();
        session.invalidate();
        return R.success("退出成功");
    }
}
